package com.yfp.operation.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.operation.domain.dto.AiModelServiceInfoDTO;
import com.yfp.operation.domain.dto.SiliconFlowRetrieveAccountInformationDTO;
import com.yfp.operation.domain.dto.SiliconFlowRetrieveModelsInformationDTO;
import com.yfp.operation.service.SiliconFlowService;
import org.springframework.stereotype.Service;

@Service
public class SiliconFlowServiceImpl implements SiliconFlowService {

    @Override
    public SiliconFlowRetrieveModelsInformationDTO retrieveModelsInformation(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        HttpResponse execute = HttpUtil.createGet(aiModelServiceInfoDTO.getApiUrl()+"/v1/models")
                .header(Header.AUTHORIZATION, "Bearer " + aiModelServiceInfoDTO.getApiKey())
                .form("type", "text")
                .form("sub_type", "chat")
                .execute();

        if (execute.isOk()) {
            SiliconFlowRetrieveModelsInformationDTO bean = JSONUtil.toBean(execute.body(), SiliconFlowRetrieveModelsInformationDTO.class);
            return bean;
        }
        throw new ServiceException(execute.body());
    }

    @Override
    public SiliconFlowRetrieveAccountInformationDTO retrieveAccountInformation(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        HttpResponse execute = HttpUtil.createGet("https://api.siliconflow.cn/v1/user/info")
                .header(Header.AUTHORIZATION, "Bearer " + aiModelServiceInfoDTO.getApiKey())
                .execute();

        if (execute.isOk()) {
            SiliconFlowRetrieveAccountInformationDTO bean = JSONUtil.toBean(execute.body(), SiliconFlowRetrieveAccountInformationDTO.class);
            return bean;
        }
        throw new ServiceException(execute.body());
    }
}
